#include "Net/Epoll.h"

#ifdef __LINUX_PLATFORM__

CEpoll::CEpoll(void)
{
	mEpollFD = -1;
	mEpollEvent = NULL;
}

CEpoll::~CEpoll(void)
{
	SAFE_DELETE_ARRAY(mEpollEvent);
}

int CEpoll::create()
{
	mEpollFD = epoll_create1(FD_CLOEXEC);
	struct epoll_event epollEvent = {0, {0}};
	epollEvent.data.ptr = this;
	epollEvent.events = EPOLLIN | EPOLLET;
	mEpollEvent = new struct epoll_event[MAX_EPOLL_EVENTS];
	epoll_ctl(mEpollFD, EPOLL_CTL_ADD, -1, &epollEvent);
}

int CEpoll::add(int socketFD)
{
	if (socketFD <= 0)
	{
		LOGW("socketFD %d less than 0 epoll add", socketFD);
		return -1;
	}

	struct epoll_event epollEvent;
	epollEvent.events = EPOLLIN | EPOLLET;
	epollEvent.data.fd = socketFD;
	epoll_ctl(mEpollFD, EPOLL_CTL_ADD, socketFD, &epollEvent);
	return 0;
}

int CEpoll::del(int socketFD)
{
	struct epoll_event epollEvent;
	epollEvent.data.fd = socketFD;
	epoll_ctl(mEpollFD, EPOLL_CTL_DEL, socketFD, &epollEvent);
}

int CEpoll::loop()
{
	memset(mEpollEvent, 0L, MAX_EPOLL_EVENTS_SIZE);
	int eventNum = epoll_wait(mEpollFD, mEpollEvent, MAX_EPOLL_EVENTS, mTimeOut);
	return eventNum;
}

void CEpoll::setTimeOut(int second, int millisecond)
{
	mTimeOut = second * 1000 + millisecond;
}

bool CEpoll::isReadable(struct epoll_event *epollEvent)
{
	if (epollEvent == NULL)
	{
		LOGW("epollEvent is NULL, in isReadable");
		return false;
	}

	return (epollEvent->events & EPOLLIN);
}

bool CEpoll::isExcept(struct epoll_event *epollEvent)
{
	if (epollEvent == NULL)
	{
		LOGW("epollEvent is NULL, in isExcept");
		return false;
	}
	return (epollEvent->events & EPOLLERR);
}

#endif